# -*- coding: utf-8 -*-
from flask import request, json

from create_js.create_js import create_json
from config.config import ROUTE_PATH, JSON_DIR


def add_route(app):
    """
    此请求钩子，匹配所有地址请求
    在此处完成：
    获取目的地址，本地没有此目的地址对应的json文件时，从真实环境获取写入本地并在本地建立路由映射关系
    :param app:
    :return:
    """

    @app.after_request
    def zock(response):
        path = request.path
        with open(ROUTE_PATH, 'r') as f:
            route = json.load(f)
            if path in route:
                json_dir = JSON_DIR + route[path][0]
                with open(json_dir, 'r') as f:
                    data = json.load(f)
                response.data = data
                response.status_code = route[path][1]
                return response
            else:
                data, status_code = create_json(request)
                response.data = data
                response.status_code = 200
                return response
